import React, { useEffect } from "react"

import type { PlasmoMessaging } from "@plasmohq/messaging"
import { sendToBackground } from "@plasmohq/messaging"

// 增加window.attachEvent兼容
declare global {
  interface Window {
    attachEvent: any
  }
}

// 扫码成功信息处理事件
const handleMessage = function (event: any) {
  const origin = event.origin
  //判断是否来自ddLogin扫码事件
  if (origin == "https://login.dingtalk.com") {
    const loginTmpCode = event.data
    //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
    const req = {
      // 请求loginService服务
      name: "loginService",
      body: {
        loginTmpCode,
        type: 1
      }
    } as PlasmoMessaging.Request<never, { loginTmpCode: string; type: number }>
    // 发送消息到background
    sendToBackground(req).then()
  }
}

// 钉钉扫码登陆组件
export const DingtalkQrLoginFrame: React.FC = () => {
  // 定义登陆配置
  // iframe 的 id
  const frameId = "dingtalk-qr-login-frame"
  // 扫码成功后的回调地址(对应后端钉钉登陆接口, 跳转后会自动装配参数sate和code)
  const url = encodeURIComponent(
    "https://web.slpzb.com/rest/v1/account/dinglogin/?state=STATE&flatdata=2"
  )
  // 钉钉开放平台应用ID
  const appid = "dingj2boitttylsscgyd"
  // iframe 的 src
  const goto = encodeURIComponent(
    `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`
  )
  // iframe 的 style
  const style = ""
  const width = "250px"
  const height = "300px"
  const href = ""
  const src = `https://login.dingtalk.com/login/qrcode.htm?goto=${goto}${
    style ? "&style=" + encodeURIComponent(style) : ""
  }${href ? "&href=" + encodeURIComponent(href) : ""}`

  // 监听 iframe 中的message事件
  useEffect(() => {
    if (typeof window.addEventListener != "undefined") {
      window.addEventListener("message", handleMessage, false)
    } else if (typeof window.attachEvent != "undefined") {
      window.attachEvent("onmessage", handleMessage)
    }
  }, [])

  return (
    <iframe
      id={frameId}
      src={src}
      width={width}
      height={height}
      sandbox="allow-forms allow-scripts allow-same-origin allow-popups"
      style={{ border: "none" }}
    />
  )
}

export default DingtalkQrLoginFrame
